package com.sc.order.core.api.web;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sc.common.dto.PageDto;
import com.sc.order.entity.order.Order;
import com.sc.order.entity.order.OrderList;
import com.sc.order.entity.order.OrderSearch;
import com.sc.order.core.service.OrderService;
import com.sc.common.annotations.WebApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
import java.util.ArrayList;
import com.sc.common.dto.WebResponseDto;
import com.sc.common.context.DefaultBusinessContext;
import java.util.Date;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.BeanUtils;
import com.sc.common.entity.admin.importexport.SysImportExport;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import com.sc.common.util.CodeGenerator;
import com.sc.common.util.MyStringUtils;
import org.apache.commons.lang3.StringUtils;
import com.sc.mq.producer.Producer4routingKey;
import java.io.IOException;
import org.springframework.core.env.Environment;

/**
 * @author: wust
 * @date: 2020-07-15 14:14:39
 * @description:
 */
@WebApi
@RequestMapping("/web/v1/OrderController")
@RestController
public class OrderController {
    @Autowired
    private OrderService orderServiceImpl;

    @Value("${spring.rabbitmq.importexcel.exchange.name}")
    private String exchangeName;

    @Value("${spring.rabbitmq.importexcel.routing-key}")
    private String routingKey;

    @Autowired
    private Environment environment;

    @Autowired
    private Producer4routingKey producer4routingKey;

   @RequestMapping(value = "/listPage",method = RequestMethod.POST)
   public WebResponseDto listPage(@RequestBody OrderSearch search){
      WebResponseDto responseDto = new WebResponseDto();

      DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

      search.setProjectId(ctx.getProjectId());
      search.setCompanyId(ctx.getBranchCompanyId());

      PageDto pageDto = search.getPageDto();
      Page page = PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
      List<Order> list = orderServiceImpl.select(search);
      if (CollectionUtil.isNotEmpty(list)) {
          List<OrderList> lists = new ArrayList<>(list.size());
          for (Order entity : list) {
              OrderList entityList = new OrderList();
              BeanUtils.copyProperties(entity,entityList);
              lists.add(entityList);
          }
          responseDto.setLstDto(lists);
      }

      BeanUtils.copyProperties(page,pageDto);
      responseDto.setPage(pageDto);
      return responseDto;
   }



   @RequestMapping(value = "",method = RequestMethod.POST)
   public WebResponseDto create(@RequestBody  Order entity){
       WebResponseDto responseDto = new WebResponseDto();
       DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
       entity.setProjectId(ctx.getProjectId());
       entity.setCompanyId(ctx.getBranchCompanyId());
       entity.setCreaterId(ctx.getAccountId());
       entity.setCreaterName(ctx.getAccountName());
       entity.setCreateTime(new Date());
       orderServiceImpl.insert(entity);
       return responseDto;
   }


   @RequestMapping(value = "",method = RequestMethod.PUT)
   public WebResponseDto update(@RequestBody  Order entity){
       WebResponseDto responseDto = new WebResponseDto();
       DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
       entity.setModifyId(ctx.getAccountId());
       entity.setModifyName(ctx.getAccountName());
       entity.setModifyTime(new Date());
       orderServiceImpl.updateByPrimaryKeySelective(entity);
       return responseDto;
   }


   @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
   public WebResponseDto delete(@PathVariable Long id){
       WebResponseDto responseDto = new WebResponseDto();
       orderServiceImpl.deleteByPrimaryKey(id);
       return responseDto;
   }



    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public WebResponseDto detail(@PathVariable Long id){
        WebResponseDto responseDto = new WebResponseDto();
        Order entity = orderServiceImpl.selectByPrimaryKey(id);
        if(entity != null){
            responseDto.setObj(entity);
        }else{
            responseDto.setFlag(WebResponseDto.INFO_WARNING);
            responseDto.setMessage("没有该记录！");
            return responseDto;
        }
        return responseDto;
    }



    /**
     *
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/importByExcel",method= RequestMethod.POST)
    public WebResponseDto importByExcel (HttpServletRequest request, @RequestParam(value = "file" , required = true) MultipartFile multipartFile) {
        WebResponseDto mm = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        String xmlName = MyStringUtils.null2String(request.getParameter("xmlName"));
        if(StringUtils.isBlank(xmlName)){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("上传文件失败，xmlName必须填。");
            return mm;
        }else if(!xmlName.matches("[A-Za-z0-9_]+")){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("上传文件失败，xmlName只能是字母、数字、下划线或三者的组合。");
            return mm;
        }


        try {

            String batchNo = CodeGenerator.genImportExportCode();
            SysImportExport sysImportExport = new SysImportExport();
            sysImportExport.setBatchNo(batchNo);
            sysImportExport.setModuleName(xmlName);
            sysImportExport.setStartTime(new Date());
            sysImportExport.setOperationType("A100601");
            sysImportExport.setStatus("A100501");
            sysImportExport.setCreaterId(ctx.getAccountId());
            sysImportExport.setCreaterName(ctx.getAccountName());
            sysImportExport.setCreateTime(new Date());


            JSONObject jsonObject = new JSONObject();
            jsonObject.put("xmlName",xmlName);
            jsonObject.put("fileBytes",multipartFile.getBytes());
            jsonObject.put("sysImportExport",sysImportExport);
            jsonObject.put("ctx",DefaultBusinessContext.getContext());
            jsonObject.put("spring.application.name",environment.getProperty("spring.application.name"));

            producer4routingKey.send(exchangeName,routingKey,jsonObject);
        }catch (IOException e){
            mm.setFlag(WebResponseDto.INFO_ERROR);
            mm.setMessage("导入失败，转换文件失败。");
            return mm;
        }
        return mm;
    }
}
